﻿var filesHtml = {};
var url = new Url();
var $Id = url.GetQueryString("orderId");
var $css = url.GetQueryString("css");
var serializer = new JSONSerializer();
$(".need_uploading img").each(function () {
    $(this).attr("data-src", this.src);
});
if ($Id) {//编辑模式，获取并绑定订单
    $("#prompt").hide();
    $.getJSON("../Handler/LoanProductOrderHandler.ashx", { type: 4, OrderId: $Id, _: Math.random() },
        function (result) {
            if (result.Status) {
                $(".btnShow").hide();
                $("#orderId").val(result.Data.Order.OrderId);
                $(".txtICard").val(result.Data.User.IDCard).attr("disabled", "disabled");
                serializer.DeSerialize($("#dataArea"), result.Data.Order);
                serializer.DeSerializeToSpan($("#userArea"), result.Data.User);
                serializer.DeSerializeToSpan($("#workInfo"), result.Data.Work);
                $("#userId").val(result.Data.User.UserId);
                $.each(result.Data.LoanItems, function (index, item) {
                    $("#FileTemplate").tmpl(item.Files).appendTo($("#fileContent"));
                    filesHtml["content" + item.AuthId] += $("#fileContent").html();
                    $("#fileContent").empty();
                });
                $("#CustomerManager").attr("data-value", result.Data.Order.CustomerManager);
                $("#TeamManager").change();
                $("select[name='ProductTypeId']").attr("disabled", "diaabled");
                loadAuthentions(result.Data.LoanItems);
                updateProgressBar();
                if (result.Data.Order.FileBack) {
                    $("#dataArea .text").attr("disabled", "disabled");
                    $(".SavePersonal").hide();
                    $(".ul1 li:contains('手续上传')").click();
                }
            } else {
                alert(result.Message);
            }
        })
}
//联动
$("#TeamManager").change(function () {
    var operId = $("#TeamManager").val();
    if (operId <= 0) {
        return;
    }
    $.getJSON("../Handler/LoanProductOrderHandler.ashx",
        { Type: 8, OperId: operId },
        function (result) {
            if (result.Status) {
                $("#CustomerManager option:gt(0)").remove();
                $.each(result.Data, function (index, item) {
                    $.tmpl("<option value='${OptId}'>${Name}</option>", item).appendTo("#CustomerManager");
                });
                var value = $("#CustomerManager").attr("data-value");
                if (value) {
                    $("#CustomerManager").val(value).removeAttr("data-value");
                }
            } else {
                alert(result.Message);
            }
        });
});

//弹框里面的查询
$(".btnSearch").click(function () {
    var $userName = $(".txtName").val();
    var $phone = $(".txtPhone").val();
    var $idCard = $(".txtIDCard").val();
    $.getJSON("../Handler/LoanUserInfo.ashx",
        { Name: $userName, Phone: $phone, IDCard: $idCard, CreateUser: true, type: 5, _: Math.random() },
        function (result) {
            if (result) {
                $(".userInfo").empty();
                $(result.Data).each(function (index, item) {
                    $("#UserTemplete").tmpl(item).appendTo($(".userInfo"));
                });
                $(".userInfo tr").css("cursor", "pointer").click(function () {
                    var loanUserId = $(this).find(".userId").text();
                    var name = $(this).find(".name").text();
                    var phone = $(this).find(".phone").text();
                    var idCard = $(this).attr("data-id");
                    var sex = $(this).attr("data-sex");
                    var age = $(this).attr("data-age");
                    var birthDate = $(this).attr("data-birthDate");
                    var companyAddress = $(this).attr("data-companyAddress");
                    var position = $(this).attr("data-position");
                    $.ajax({
                        type: "post",
                        url: "../Handler/LoanUserInfo.ashx",
                        dataType: "json",
                        data: { Type: 6, UserId: loanUserId, _: Math.random() },
                        async: true,
                        cache: true,
                        complete: function () {
                        },
                        success: function (result) {
                            if (result.Status) {
                                $(".Name").text(name);
                                $(".Phone").text(phone);
                                $(".IDCard").text(idCard);
                                $(".Sex").text(sex);
                                $(".Age").text(age);
                                $(".BirthDate").text(birthDate);
                                $(".CompanyAddress").text(companyAddress);
                                $(".Position").text(position);
                                $("#userId").val(loanUserId);
                            }
                            else {
                                alert(result.Message);
                            }
                        }
                    });


                });
            }
        });
});

//点击文本框 弹框
$(".txtICard").focus(function () {
    $(".btnShow").click();
});

$(".ul1 li:contains('手续上传')").click(function () {
    if (!$("#orderId").val()) {
        setTimeout(function () {
            $(".ul1 li:contains('项目建立')").click();
        }, 10);
        alert("请先完善项目信息！");
        return;
    }
});
//加载验证项目
function loadAuthentions(items) {
    var $productId = $("select[name='ProductTypeId']").val();
    if (!$productId || $productId <= 0) {
        setTimeout(function () {
            $(".ul1 li:contains('项目建立')").click();
        }, 10);
        $(".errorProductType").text("请先选择一个有效的产品类型！");
        return;
    }
    var $value = $("select[name='ProductTypeId']").attr("data-value");
    if ($value === $productId) {
        return;
    }
    $.getJSON("../Handler/ProductHandler.ashx",
        { Id: $productId, Type: 5, _: Math.random() },
        function (result) {
            if (result.Status) {
                $("select[name='ProductTypeId']").attr("data-value", $productId);
                $("#necessaryFiles").empty();
                $("#optionalFiles").empty();
                if (result.Count <= 0) {
                    $("#save,#submit").hide();
                    $(".errorProductType").text("您选择的产品类型没有要上传的认证信息！");
                    $(".ul1 li:contains('项目建立')").click();
                    return;
                }
                $("#save,#submit").show();
                $.each(result.Data, function (index, item) {
                    item.Src = "../img/4.jpg";
                    item.Attr = "false";
                    if (filesHtml["content" + item.AuthId] != undefined && filesHtml["content" + item.AuthId] != "undefined") {
                        var matches = filesHtml["content" + item.AuthId].match(/src=\"(.*?)\"/);
                        item.Src = matches ? matches[1] : item.Src;
                        item.Attr = "true";
                    }
                    if (items) {
                        $.each(items, function () {
                            if (this.AuthId === item.AuthId) {
                                if (this.Verified) {
                                    if (this.Passed) {
                                        item.VerifyInfo = "(已通过)";
                                    } else {
                                        item.VerifyInfo = "(未通过)";//:" + this.VerifyOpinion + ")";
                                        item.Opinion = "退回意见：" + this.VerifyOpinion;
                                    }
                                }
                                return false;
                            }
                        });
                    }
                    var dom = item.IsRequired ? $("#necessaryFiles") : $("#optionalFiles");
                    $("#AuthentionTemplate").tmpl(item).appendTo(dom).find(".openLayout").click(function () {
                        var authId = $(this).attr("data-authid");
                        $("#authId").val(authId);
                        $(".completelist").empty();
                        if (filesHtml["content" + item.AuthId] != undefined && filesHtml["content" + item.AuthId] != "undefined") {
                            $(".completelist").html(filesHtml["content" + authId]);
                        }
                        bindClickEvent();
                    });
                    if (items) {
                        $.each(items, function () {
                            if (this.Verified && this.Passed) {
                                $("div[data-authid='" + this.AuthId + "']").css('opacity', '0.5').find(".openLayout").removeAttr("data-toggle").unbind("click").click(function () {
                                    alert("已通过认证，无法进行添加或者修改！");
                                    return false;
                                });
                            }
                        });
                    }
                });
                bindClickEvent();
                updateProgressBar();
            } else {
                alert(result.Message);
            }
        });
}

//保存立项基础信息，非空验证
$(".SavePersonal").click(function () {
 
    var errorNode = null;
    $("#dataArea .text").each(function () {
        if (!$(this).val() || $(this).val() == -1) {
            $name = $(this).attr("data-name");
            errorNode = $(this);
            $(this).next("span").text($name + "不能为空！");
            $(this).focus();
            return false;
        }
    });
    if (errorNode) {
        return;
    }
    var userId = $("#userId").val();
    if (!userId) {
        alert("请添加借款人信息！");
        $(".btnShow").click();
        return;
    }
    var serializer = new JSONSerializer();
    var $formData = serializer.Serialize($("#dataArea")[0]);
    $formData.type = $Id ? 2 : 1;
    $formData.UserId = userId;
    var ddfinancialId = $("#DDFinancialID").val();
    if (ddfinancialId == undefined || ddfinancialId == "") {
        $formData.DDFinancialID = 0;
    } else {
        $formData.DDFinancialID = ddfinancialId;
    } 
    $formData._ = Math.random()
    if ($Id) {
        $formData.OrderId = $Id;
    }
    $.getJSON(
        "../Handler/LoanProductOrderHandler.ashx",
        $formData,
        function (result) {
            alert(result.Message);
            if (result.Status) {
                $("#orderId").val(result.Data);
                loadAuthentions();
                $("li:contains('手续上传')").click();
            }
        }
    );
    return false;
});

//change事件
$(".text").change(function () {
    $(this).next("span").empty();
});

function getFormData() {
    return [{ name: "type", value: 4 }, { name: "OrderId", value: $("#orderId").val() }, { name: "AuthId", value: $("#authId").val() }];
}

//上传
$(".btn_upload").click(function () { $("#fileupload").click() });
$('#fileupload').fileupload({
    limitMultiFileUploadSizeOverhead: 512,
    limitMultiFileUploads: 2,
    dataType: 'json',
    singleFileUploads: false,
    formData: getFormData,
    add: function (e, data) {
        if (!validateFile(data.files)) {
            return false;
        }
        data.submit();
    },
    done: function (e, data) {
        if (data.result.Status) {
            $("#FileTemplate").tmpl(data.result.Data).appendTo(".completelist");
            bindClickEvent();
            filesHtml["content" + $("#authId").val()] = $(".completelist").html();
            $(".need_uploading img[data-authid='" + $("#authId").val() + "']")
                .attr("src", $(".completelist img:eq(0)").attr("src"))
                .parent("div").attr("data-upload", true);
            updateProgressBar();
        }
        else {
            alert(data.result.Message);
        }
    }
});
//删除文件
function bindClickEvent() {
    $(".completelist :button").click(function () {
        if (confirm("确定要删除？")) {
            var $imgId = $(this).attr("data-id");
            var $that = $(this);
            $.getJSON(
                "../Handler/FileHandler.ashx",
                { type: 5, FileId: $imgId, _: Math.random() },
                function (result) {
                    if (result.Status) {
                        $that.parents("tr").remove();
                        filesHtml["content" + $("#authId").val()] = $(".completelist").html();
                        var dom = $(".need_uploading img[data-authid='" + $("#authId").val() + "']");
                        if ($(".completelist tr").length <= 0) {
                            dom.attr("src", dom.attr("data-src"));
                            //dom.parent("div").removeAttr("data-upload");
                            dom.parent("div").attr("data-upload", "false");
                            updateProgressBar();
                        }
                        else {
                            dom.attr("src", $(".completelist img:eq(0)").attr("src"));
                        }
                    }
                    else {
                        alert(result.Message);
                    }
                });
        }
    });
}
//保存
$("#save").click(function () {
    var result = true;
    $("#necessaryFiles").each(function (index, item) {
        var isUpload = $(this).attr("data-upload");
        if (isUpload == false) {
            result = false;
            alert("您的必要上传资料上传不完整！");
            return false;
        }
    });
    if (result) {
        alert("保存成功！");
    }
    return false;
});

//提交
$("#submit").click(function () {
    var array = [];
    $("#necessaryFiles").children("div[data-upload='false']").each(function (index, item) {
        array.push($(this).children("p:eq(0)").text());
    });
    if (array.length > 0) {
        $("#prompt").css("display", "block").text("请上传以下信息：" + array.join(","));
        return;
    }
    $.getJSON("../Handler/LoanProductOrderHandler.ashx",
        { OrderId: $("#orderId").val(), Type: 7, _: Math.random() },
        function (result) {
            if (result.Status) {
                alert("提交成功！");
                location.href = "../View/LoanOrderList.aspx?css=1017";
            }
            else {
                alert(result.Message);
            }
        }
        );
});


//更新进度条
function updateProgressBar() {
    var total = 0;
    if ($("#orderId").val()) {
        total += 50;
    }
    var count = $("#necessaryFiles").children("div").length;
    if (count > 0) {
        var uploadCount = $("#necessaryFiles").children("div[data-upload=true]").length;
        total += (uploadCount / count) * 50;
    }
    total = total.toFixed(2);
    $(".progressBar").text(total + "%").css("width", total + "%");
}

//对上传文件进行验证
function validateFile(files) {
    var result = true;
    $.each(files, function (index, file) {
        if (!/.(gif|jpg|jpeg|png)$/.test(file.name.toLowerCase())) {
            alert("图片类型必须是.gif,jpeg,jpg,png中的一种");
            result = false;
            return false;
        }
        if (file.size > 500 * 1024) {
            alert("文件大小不能超过500KB！");
            result = false;
            return false;
        }
    });
    return result;
}